package com.xiaohai.wx.weather.scheduler;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import com.xiaohai.wx.weather.dao.WeatherDao;
import com.xiaohai.wx.weather.dto.Weather;
import com.xiaohai.wx.weather.dto.User;
import com.xiaohai.wx.weather.message.SessionHandler;
import com.xiaohai.wx.weather.service.LocationService;
import com.xiaohai.wx.weather.service.UserService;
import com.xiaohai.wx.weather.service.WeatherService;
import com.xiaohai.wx.weather.service.WeixinPlatformAgent;
import com.xiaohai.wx.weather.util.DateUtil;
import com.xiaohai.wx.weather.util.MessageUtil;


@Service("AppScheduler")
public class AppScheduler {
	
	Logger logger = Logger.getLogger(this.getClass().getName());
	
	@Autowired
	WeatherService weatherService;
	
	@Autowired
	WeixinPlatformAgent weixinAgent;
	
	@Autowired
	LocationService locationService;
	
	@Autowired
	UserService userService;
	
	@Scheduled(cron="0 0,30 * * * *")
	public void clearSessionMap(){
		SessionHandler.clearSession();
	}
	
	@Scheduled(cron="0 0 0 * * *")
	public void clearDataCacheMap(){
		WeatherDao.clearAll();
	}
	
	@Scheduled(cron="0 0 5,17 * * *")
	//@Scheduled(fixedRate = 3600000)
	//@Autowired
	public void sendWeather_getFakeId() throws Exception{
		
		logger.debug("Begin to broadcast weather as scheduled!");
		
		List<User> allUsersInDB = userService.getAllConsumerFromDB();
		
		if(allUsersInDB == null || allUsersInDB.isEmpty()){
			return;
		}
		
		weixinAgent.login();
		
		List<User> goodUserList = getFakeIdUser(allUsersInDB);
		
		sendMsgToList(goodUserList);
		
	}
	
	private List<User> getFakeIdUser(List<User> allUsersInDB){
		
		List<String> excludes = new ArrayList<String>();
		Map<String, User> keyUserMap = new HashMap<String, User>();
		List<User> goodUserList = new ArrayList<User>();
		
		for(User user : allUsersInDB){
			
			if(StringUtils.isBlank(user.getFakeId())){
				keyUserMap.put(user.getMapKey(), user);
			}else{
				excludes.add(user.getFakeId());
				goodUserList.add(user);
			}
		}		
		
		List<User> goodUserList2 = new ArrayList<User>();
		if(!keyUserMap.isEmpty()){
			goodUserList2 = weixinAgent.matchUser(keyUserMap, excludes);
			if(goodUserList2 != null && !goodUserList2.isEmpty()){				
				for(User user : goodUserList2){
					userService.addOrReplaceConsumerToDB(user);
				}
			}
		}
		
		goodUserList.addAll(goodUserList2);
		return goodUserList;
	}
	
	private void sendMsgToList(List<User> goodUserList){
		
		Map<String, String> cityNameWeatherMap = new HashMap<String, String>();
		
		for(User user : goodUserList){
			
			if(StringUtils.isBlank(user.getLocation())){
				continue;
			}
			
			logger.debug("begin to send msg to user "+ user.getRemarkName()+", fakeId: "+ user.getFakeId());
			
			String cityNameList = user.getLocation();
			String[] cityNameArray = cityNameList.split(",");
			StringBuilder msgSB = new StringBuilder();
			
			for(int i=0; i< cityNameArray.length; i++ ){
				
				String cityName = cityNameArray[i];
				
				String weatherContent = "";
				
				if(cityNameWeatherMap.containsKey(cityName)){
					weatherContent = cityNameWeatherMap.get(cityName);
				}else{
					List<Weather> weatherList = weatherService.getWeather(cityName);
					if(weatherList == null || weatherList.isEmpty()){
						weatherContent = "";
					}else{
						if(DateUtil.nowIsMorning()){
							weatherContent = MessageUtil.getTodayWeatherStr(weatherList, cityName);
						}else{
							weatherContent = MessageUtil.getTomorrowWeatherStr(weatherList, cityName);
						}
						
						cityNameWeatherMap.put(cityName, weatherContent);
					}
				}
				
				msgSB.append(weatherContent);
				msgSB.append("\n\n");
			}
			
			String msg = msgSB.substring(0, msgSB.length()-2);
			//logger.debug("weather for cities: "+ msg);
			
			try {
				weixinAgent.sendMsgToSingleUser(msg, user.getFakeId());
			} catch (IOException e) {
				logger.error("Send Msg to Single User Error, UserFakeId is: "+ user.getFakeId(), e);
			}
		}		
		
		cityNameWeatherMap.clear();
	}
	
	//@Autowired
	public void testSendMsg() throws Exception{
		User user = new User();
		user.setFakeId("2158311300");
		user.setLocation("北京,蚌埠");
		List<User> userList = new ArrayList<User>();
		userList.add(user);
		
		weixinAgent.login();
		this.sendMsgToList(userList);
	}

	
}
